package com.socialrss.utils.twitter;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;

import com.socialrss.R;
import com.socialrss.accounts.AccountOwner;
import com.socialrss.constants.SocialNetworkNames.SocialNetKeys;
import com.socialrss.utils.SocialRssModel;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

public class TwitterUtil {

	// Constants
	/**
	 * Keys from here https://dev.twitter.com/apps/ consumer key and secret
	 * */
	protected static String TWITTER_CONSUMER_KEY = "TFmRirUeLYylcfIYXjoA";
	protected static String TWITTER_CONSUMER_SECRET = "BsEbceLxVx9FQrTcWrCW7khtGON6T6y8QfXUaPOd4c";

	// Preference Constants
	static String PREFERENCE_NAME = "twitter_oauth";
	static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
	static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
	static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

	public static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

	// Twitter oauth urls
	static final String URL_TWITTER_AUTH = "auth_url";
	public static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
	static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

	// Twitter
	private static Twitter twitter;
	private static RequestToken requestToken;

	/**
	 * Function to login twitter
	 * */
	public static void loginToTwitter(Activity activity) {
		// Check if already logged in
		if (!isTwitterLoggedInAlready()) {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
			Configuration configuration = builder.build();

			TwitterFactory factory = new TwitterFactory(configuration);
			twitter = factory.getInstance();

			try {
				requestToken = twitter
						.getOAuthRequestToken(TWITTER_CALLBACK_URL);
				activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri
						.parse(requestToken.getAuthenticationURL())));
			} catch (TwitterException e) {
				e.printStackTrace();
			}
		} else {
			// user already logged into twitter
			Toast.makeText(activity.getApplicationContext(),
					"Already Logged into twitter", Toast.LENGTH_LONG).show();
		}
	}

	public static boolean isKeysNotSet() {
		return TWITTER_CONSUMER_KEY.trim().length() == 0
				|| TWITTER_CONSUMER_SECRET.trim().length() == 0;
	}

	/**
	 * Function to logout from twitter It will just clear the application shared
	 * preferences
	 * */
	public static void logoutFromTwitter() {
		SocialRssModel.Instance(null).removeSocialAccount(SocialNetKeys.tw.toString());
	}

	public static String setoAuthVerf(Uri uri) {
		// oAuth verifier
		String verifier = uri
				.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

		try {
			// Get the access token
			//AccessToken accessToken = twitter.getOAuthAccessToken( requestToken, verifier);

			
			
			// After getting access token, access token secret
			// store them in application preferences
			//SocialRssModel.Instance(null).addNewSocialNetworkReqToken(SocialNetKeys.tw.toString(), accessToken.getTokenSecret(), accessToken.getToken(), "1", "1", "1");
			
			TwitterLogin tl = new TwitterLogin();
			tl.execute(verifier);

			Log.e("Twitter OAuth Token", "> " + "Token Created");

			
			// Getting user details from twitter
			// For now i am getting his name only
			//long userID = accessToken.getUserId();
			//User user = twitter.showUser(userID);
			//String username = user.getName();
			return null;
			
		} catch (Exception e) {
			// Check log for login errors
			return "Error";
		}

	}

	/**
	 * Check user already logged in your application using twitter Login flag is
	 * fetched from Shared Preferences
	 * */
	public static boolean isTwitterLoggedInAlready() {
		// return twitter login status from Shared Preferences
		AccountOwner owner = SocialRssModel.Instance(null).getAccessTokenOfSocialNet(SocialNetKeys.tw.toString());
		return owner.isValid();
	}

	
	
	public static class UpdateTwitterStatus extends AsyncTask<String, String, String> {

		private Activity activity;
		// Progress dialog
		ProgressDialog pDialog;
		
		public UpdateTwitterStatus( Activity activity) {
			this.activity = activity;
		}
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(activity);
			pDialog.setMessage("Updating to twitter...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Places JSON
		 * */
		protected String doInBackground(String... args) {
			Log.d("Tweet Text", "> " + args[0]);
			String status = args[0];
			try {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
				builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
				
				AccountOwner owner = SocialRssModel.Instance(null).getAccessTokenOfSocialNet(SocialNetKeys.tw.toString());
				// Access Token
				String access_token = owner.getAccessToken();
				// Access Token Secret
				String access_token_secret = owner.getSecret_token();
				
				AccessToken accessToken = new AccessToken(access_token, access_token_secret);
				Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
				// Update status
				twitter4j.Status response = twitter.updateStatus(status);
				
				Log.d("Status", "> " + response.getText());
			} catch (TwitterException e) {
				// Error in updating status
				Log.d("Twitter Update Error", e.getMessage());
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog and show
		 * the data in UI Always use runOnUiThread(new Runnable()) to update UI
		 * from background thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			activity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(activity.getApplicationContext(),
							"Status tweeted successfully", Toast.LENGTH_SHORT)
							.show();
					// Clearing EditText field
					EditText txtUpdate = (EditText) activity.findViewById(R.id.txtUpdateStatus);
					txtUpdate.setText("");
				}
			});
		}

	}
	
	public static class TwitterLogin extends AsyncTask<String, Void, AccessToken> {
		

		/**
		 * getting Places JSON
		 * */
		protected AccessToken doInBackground(String... args) {
			AccessToken accessToken = null;
			try {
				accessToken = twitter.getOAuthAccessToken(
						requestToken, args[0]);
			} catch (TwitterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return accessToken;
			
		}
		protected void onPostExecute(AccessToken accessToken) {
			SocialRssModel.Instance(null).addNewSocialNetworkReqToken(SocialNetKeys.tw.toString(), accessToken.getTokenSecret(), accessToken.getToken(), "1", "1", "1");
		}
		

	}
	
}
